package com.roocon.thread.daemon;

public class ClientJoin {

  private Thread executeThread;

  private volatile boolean finished = false;

  public static void main(String[] args) throws InterruptedException {
    ClientJoin client = new ClientJoin();
    client.execute(() -> {
      while (!client.finished) {
        String name = Thread.currentThread().getName();
        System.out.println("Name:" + name + " ===Finish===");
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });

    Thread.sleep(3_000);
    client.executeThread.interrupt();
  }

  public void execute(Runnable task) {
    executeThread = new Thread("ThreadService") {
      @Override public void run() {
        Thread runner = new Thread(task, "Daemon-thread");
        runner.setDaemon(true);
        runner.start();
        try {
          runner.join();
        } catch (InterruptedException e) {
          finished = true;
          //e.printStackTrace();
          String name = Thread.currentThread().getName();
          System.out.println("Name:" + name + "\tFinish task ... " + e.toString());
        }
      }
    };
    executeThread.start();
  }
}
